package com.originskyseed.platform.user.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.originskyseed.platform.user.model.*;
import com.originskyseed.platform.user.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.vo.request.SalesmanLevelaRequestVO;

/**
 * 业务员等级体系Controller类（OSI_SALESMAN_LEVEL）
 *
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/salesmanLevel")
@BaseLocaleResource(localeFileName = "i18n_user")
public class SalesmanLevelController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SalesmanLevelController.class);

	@DubboReference
	private ISalesmanLevelService salesmanLevelaService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private ILevelTravelService levelTravelService;

	@DubboReference
	private ISalesmanRelateLevelService salesmanRelateLevelService;

	@DubboReference
	private ILevelSystemService levelSystemService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/salesmanLevelaList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<SalesmanLevel>> salesmanLevelaList(HttpServletRequest request) {
		BaseResponseBody<BasePage<SalesmanLevel>> result = null;
		try {
			// 请求对象
			SalesmanLevelaRequestVO requestVO = this.getParameterBean(SalesmanLevelaRequestVO.class);
			requestVO.setIsDel(2);
			// 分页查询
			BasePage<SalesmanLevel> page = new BasePage<SalesmanLevel>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.salesmanLevelaService.selectListByPage(requestVO.toMap(), page);
			for (SalesmanLevel salesmanLevel:page.getResults()) {
				LevelSystem levelSystem = this.levelSystemService.selectByPrimaryKey(salesmanLevel.getSystemId());
				if(levelSystem!=null){
					salesmanLevel.setSystemName(levelSystem.getTitle());
				}
			}
			result = new BaseResponseBody<BasePage<SalesmanLevel>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<SalesmanLevel>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * PK广场选择pk对象分页列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPkObjList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PkObjUserInfoVO>> selectPkObjList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PkObjUserInfoVO>> result = null;
		try {
			// 请求对象
			SalesmanLevelaRequestVO requestVO = this.getParameterBean(SalesmanLevelaRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 分页查询
			BasePage<PkObjUserInfoVO> page = new BasePage<PkObjUserInfoVO>(requestVO.getPageNo(), requestVO.getPageSize());
			String LoginUser = userInfo.getId();
			// 主播
			if (userInfo.getSourceSys() == 1) {
				if (userInfo.getType() == 7 || userInfo.getType() == 8) {
					return new BaseResponseBody<BasePage<PkObjUserInfoVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.LIMIT_OBJ_PK.getMsg()), null);
				}
				if (userInfo.getType() == 11) {
					page = this.salesmanLevelaService.selectPkAnchorObjListByPage(requestVO.toMap(), page, LoginUser);
				} else {
					page = this.salesmanLevelaService.selectPkDeptObjListByPage(requestVO.toMap(), page, userInfo);
				}
			}
			// 业务员
			if (userInfo.getSourceSys() == 2) {
				if (userInfo.getType() == 0 || userInfo.getType() == 1) {
					return new BaseResponseBody<BasePage<PkObjUserInfoVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.LIMIT_OBJ_PK.getMsg()), null);
				}
				if (userInfo.getType() == 6) {
					page = this.salesmanLevelaService.selectPkSalesManObjListByPage(requestVO.toMap(), page, LoginUser);
				} else {
					page = this.salesmanLevelaService.selectPkDeptObjListByPage(requestVO.toMap(), page, userInfo);
				}
			}
			result = new BaseResponseBody<BasePage<PkObjUserInfoVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PK_OBJ_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PkObjUserInfoVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PK_OBJ_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/salesmanLevelaSave.json", method = RequestMethod.POST)
	@RequiredParams(names = { "levelName", "systemId", "empiricValueMin", "empiricValueMax", "medalPic", "attenuationValue", "basePay" })
	public BaseResponseBody salesmanLevelaSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			SalesmanLevel salesmanLevela = this.getParameterBean(SalesmanLevel.class);

			if (salesmanLevela.getEmpiricValueMin().compareTo(BigDecimal.ZERO) < 0 || salesmanLevela.getEmpiricValueMax().compareTo(BigDecimal.ZERO) < 0 || salesmanLevela.getAttenuationValue().compareTo(BigDecimal.ZERO) < 0 || salesmanLevela.getBasePay().compareTo(BigDecimal.ZERO) < 0) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.VALUE_CANNOT_BE_NEGATIVE.getMsg()), false);
			} else if (salesmanLevela.getEmpiricValueMax().compareTo(salesmanLevela.getEmpiricValueMin()) <= 0) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.LEVEL_EXPERIENCE_INTERVAL_ERROR.getMsg()), false);
			} else if (this.salesmanLevelaService.selectEmpiricValue(salesmanLevela)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.REPEATED_EXPERIENCE_VALUE_ERROR.getMsg()), false);
			}

			if (StringUtils.isNotBlank(salesmanLevela.getId())) {
				this.salesmanLevelaService.updateByPrimaryKey(salesmanLevela);
			} else {
				salesmanLevela.setCreatorId(userInfo.getId());
				salesmanLevela.setCreator(userInfo.getName());
				salesmanLevela.setIsDel(2);
				this.salesmanLevelaService.insertSelective(salesmanLevela);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), salesmanLevela);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/salesmanLevelaDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> salesmanLevelaDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			//this.salesmanLevelaService.deleteByPrimaryKeys(Arrays.asList(ids));
			this.salesmanLevelaService.updateByIds(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 设置峰值
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updatePeakValue.json", method = RequestMethod.POST)
	@RequiredParams(names = { "peakValue" })
	public BaseResponseBody updatePeakValue(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			Integer peakValue = this.getParameterInteger("peakValue", null);

			this.salesmanLevelaService.updatePeakValue(peakValue);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据id查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectSalesmanLevel.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectSalesmanLevel(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			SalesmanLevel salesmanLevela = this.salesmanLevelaService.selectByPrimaryKey(id);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), salesmanLevela);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据经验值查询等级名称
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectLevelNameByEmpValue.json", method = RequestMethod.POST)
	@RequiredParams(names = { "empiricValue" })
	public BaseResponseBody selectLevelNameByEmpValue(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			BigDecimal empiricValue = new BigDecimal(this.getParameterInteger("empiricValue", null));
			String belongDeptId = this.getParameterString("belongDeptId",null);
			String id = this.salesmanLevelaService.selectLevelIdByEmpiricValue(empiricValue,belongDeptId);
			if (StringUtils.isNotEmpty(id)) {
				SalesmanLevel salesmanLevela = this.salesmanLevelaService.selectByPrimaryKey(id);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), salesmanLevela.getLevelName());
			} else {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.NOT_FIND_SALESMAN_LEVEL_ERROR.getMsg()), false);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectSalesmanLevelaList.json", method = RequestMethod.POST)
	public BaseResponseBody selectSalesmanLevelaList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			SalesmanLevel salesmanLevela = this.getParameterBean(SalesmanLevel.class);

			List<SalesmanLevel> salesmanLevelaList = this.salesmanLevelaService.selectList(salesmanLevela);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), salesmanLevelaList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 查询列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectLevelByUserId.json", method = RequestMethod.POST)
	@RequiredParams(names = { "userId" })
	public BaseResponseBody selectLevelByUserId(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String userId= this.getParameterString("userId","");
			UserInfo userInfo=userInfoService.selectByPrimaryKey(userId);
			String deptId="";
			if(userInfo!=null)
			{
				deptId=userInfo.getDeptId();
			}
			else
			{
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_IS_NULL.getMsg()),"", null);
				return result;
			}
			//SalesmanLevel salesmanLevela = this.getParameterBean(SalesmanLevel.class);
			//List<SalesmanLevel> salesmanLevelaList = this.salesmanLevelaService.selectList(salesmanLevela);
			List<SalesmanLevel> salesmanLevelaList =this.salesmanLevelaService.selectListByDeptId(deptId);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), salesmanLevelaList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存员工等级信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveLevelByUserId.json", method = RequestMethod.POST)
	@RequiredParams(names = { "userId","levelId" })
	public BaseResponseBody saveLevelByUserId(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String userId= this.getParameterString("userId","");
			String levelId= this.getParameterString("levelId","");
			userInfoService.updateLevelIdByUserId(userId,levelId);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.UPDATE_STATE_SUCCESS.getMsg()),null);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.UPDATE_STATE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}
	/**
	 * 查询成长轨迹
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectGrowthTrajectory.json", method = RequestMethod.POST)
	public BaseResponseBody selectGrowthTrajectory(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			List<Map<String, Object>> mapList = new ArrayList<>();
			// 请求对象
			String account = this.getParameterString("staffAccount", null);

			UserInfo userInfo = this.userInfoService.selectByAccount(account);
			SalesmanRelateLevel salesmanRelateLevel = this.salesmanRelateLevelService.selectByAccount(userInfo.getAccount());

			LevelTravel query = new LevelTravel();
			query.setUserId(userInfo.getId());
			query.setType(0);
			List<LevelTravel> levelTravels = this.levelTravelService.selectList(query);

			List<SalesmanLevel> salesmanLevelaList = this.salesmanLevelaService.selectList(new SalesmanLevel());
			for (SalesmanLevel salesmanLevela : salesmanLevelaList) {
				boolean flag = true;
				for (LevelTravel levelTravel : levelTravels) {
					if (salesmanLevela.getId().equals(levelTravel.getLevelId())) {
						flag = false;
						Map<String, Object> map = new HashMap<>();
						map.put("levelName", salesmanLevela.getLevelName());
						map.put("reachTime", levelTravel.getCreateTime());
						map.put("value", null);
						map.put("medalPic", salesmanLevela.getMedalPic());
						if (salesmanRelateLevel != null && salesmanRelateLevel.getLevelId().equals(salesmanLevela.getId())) {
							map.put("isCrrent", 1);
						} else {
							map.put("isCrrent", 0);
						}
						mapList.add(map);
						break;
					}
				}
				if (flag) {
					Map<String, Object> map = new HashMap<>();
					map.put("levelName", salesmanLevela.getLevelName());
					map.put("reachTime", salesmanRelateLevel.getUpdateTime());
					map.put("value", salesmanLevela.getEmpiricValueMin());
					map.put("medalPic", salesmanLevela.getMedalPic());
					if (salesmanRelateLevel != null && salesmanRelateLevel.getLevelId().equals(salesmanLevela.getId())) {
						map.put("isCrrent", 1);
					} else {
						map.put("isCrrent", 0);
					}
					mapList.add(map);
				}
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), mapList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}
}
